package com.shen.cloud.controller;

import com.shen.cloud.pojo.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class DepartmentConsuController {
    @Autowired
    RestTemplate restTemplate;

    //请求地址 如果只有一个EurekaServer就可以指定固定的服务访问地址
   // private static final String REST_URL_PREFIX = "http://localhost:8001";
    //如果有多个EurekaServer那需要访问不同的EurekaServer，这里的地址就不可能是固定的地址
    //可以指定固定的服务instance名，来实现访问指定的服务
    private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-EUREKA-CLIENT-PRO-8001";

    /**
     * 获得对应id的department
     * @param id
     * @return
     */
    @RequestMapping("/consumer/dept/get/{id}")
    public Department get(@PathVariable("id")Long id){
      return   restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id,Department.class);
    }

    /**
     *增加department
     * @param department
     * @return
     */
    @RequestMapping("/consumer/dept/add")
    public boolean insertDepartment(Department department){
        return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add/",department,Boolean.class);
    }

    /**
     * 获取所有department
     * @return
     */
    @RequestMapping("/consumer/departs/list")
    public List<Department> selectAllDepartment(){
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list/",List.class);
    }


    //获取服务的配置信息
    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * public interface ServiceInstance {
     *     String getServiceId();
     *
     *     String getHost();
     *
     *     int getPort();
     *
     *     boolean isSecure();
     *
     *     URI getUri();
     *
     *     Map<String, String> getMetadata();
     * }
     */
    @GetMapping("/get/discover")
    public Object discover(){
        List<String> services = discoveryClient.getServices();
        System.out.println("discover=>service:"+services);
        List<ServiceInstance> instances = discoveryClient.getInstances("springcloud-eureka-client-pro-8001");
        for (ServiceInstance instance : instances) {
            System.out.println("ServiceId: "+instance.getServiceId()+"\t"+
                    "Host: "+instance.getHost()+"\t"+
                    "Port: "+instance.getPort()+"\t"+
                    "isSecure: "+instance.isSecure()+"\t"+
                    "Uri: "+instance.getUri()+"\t");
        }
        return  instances;
    }
}
